package ms.unicorn.erml.edit.parts;

import ms.unicorn.erml.edit.policies.EntityCompartmentItemSemanticEditPolicy;
import ms.unicorn.erml.figures.CompartmentFigure;
import ms.unicorn.modellanguage.LanguageEntity;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.LayoutAnimator;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeCompartmentEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.CreationEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.ResizableCompartmentEditPolicy;
import org.eclipse.gmf.runtime.notation.BasicCompartment;
import org.eclipse.gmf.runtime.notation.NotationPackage;
import org.eclipse.gmf.runtime.notation.View;

public abstract class ContainerEntityCompartmentEditPart extends
		ShapeCompartmentEditPart {

	public ContainerEntityCompartmentEditPart(View view) {
		super(view);
	}

	protected abstract LanguageEntity getContainerLanguageEntity();

	@Override
	public CompartmentFigure getFigure() {
		return (CompartmentFigure) super.getFigure();
	}
	
	public IFigure createFigure() {
		CompartmentFigure figure = new CompartmentFigure(
				getCompartmentName(), getMapMode());
		figure.getContentPane().setLayoutManager(getLayoutManager());
		figure.getContentPane().addLayoutListener(LayoutAnimator.getDefault());
		figure.setBorder(null);
		figure.setTitleVisibility(true);
		if (!isExpanded())
			figure.setCollapsed();
		return figure;
	}

	@Override
	public ContainerEntityEditPart getParent() {
		return (ContainerEntityEditPart)super.getParent();
	}

	@Override
	protected void createDefaultEditPolicies() {
		super.createDefaultEditPolicies();
		installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE, 
				new EntityCompartmentItemSemanticEditPolicy(getContainerLanguageEntity()));
		installEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE,
				new ResizableCompartmentEditPolicy());
		installEditPolicy(EditPolicyRoles.CREATION_ROLE,
				new CreationEditPolicy());
	}

	@Override
	protected void handleNotificationEvent(Notification event) {
		super.handleNotificationEvent(event);
		Object feature = event.getFeature();
		
		if (NotationPackage.eINSTANCE.getDrawerStyle_Collapsed().equals(feature)) {
			boolean collapsed = event.getNewBooleanValue();
			if (collapsed) {
				getFigure().setCollapsed();
				getParent().setCollapse(collapsed);
			}
			else {
				getParent().setCollapse(collapsed);
				getFigure().setExpanded();
			}
				
		}
	}

	public boolean isExpanded() {
		Object model = basicGetModel();
		if (model instanceof BasicCompartment) 
			return !((BasicCompartment) model).isCollapsed();
		return getFigure() != null ? getFigure().isExpanded() : false;
	}

}